//
//  DigitalExchangeTradeViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/13.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "DigitalExchangeTradeViewController.h"
#import "HYNetHelper.h"
#import "ExchangeDetailsViewController.h"

@interface DigitalExchangeTradeViewController ()
@property (weak, nonatomic) IBOutlet UILabel *expiresLabel;

@property (weak, nonatomic) IBOutlet UILabel *ccy1Label;
@property (weak, nonatomic) IBOutlet UILabel *ccy1Amount;
@property (weak, nonatomic) IBOutlet UILabel *ccy2Label;
@property (weak, nonatomic) IBOutlet UILabel *ccy2Amount;
@property (weak, nonatomic) IBOutlet UILabel *rate1;
@property (weak, nonatomic) IBOutlet UILabel *rate2;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *tradeButton;

@property (nonatomic, assign) NSInteger expiresSeconds;

@property (nonatomic, strong) NSString *traderId;

@end

@implementation DigitalExchangeTradeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.ccy1Label.text = self.ccy1;
    self.ccy2Label.text = self.ccy2;
    self.ccy1Amount.text = self.amount;
    
    self.rate1.text = [NSString stringWithFormat:@"1 %@ = %@ %@", self.ccy1, @"--", self.ccy2];
    self.rate2.text = [NSString stringWithFormat:@"1 %@ = %@ %@", self.ccy2, @"--", self.ccy1];
    
    NSString *string = [NSString stringWithFormat:@"%@ -- %@", JFMainLocalizedString(@"exchange.expires-in"), JFMainLocalizedString(@"exchange.seconds")];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:string];
    [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xFFA000)} range:[string rangeOfString:@(self.expiresSeconds).stringValue]];
    self.expiresLabel.attributedText = attStr;
    
    self.title = JFMainLocalizedString(@"exchange.exchange");
    [self.tradeButton setTitle:JFMainLocalizedString(@"exchange.do-trade") forState:UIControlStateNormal];
    [self.cancelButton setTitle:JFMainLocalizedString(@"cancel") forState:UIControlStateNormal];
    
    [self request];
}

- (void)request {
    WEAKSELF
    [SLRemindView showHUDAddedTo:self.view animated:YES];
    
    [HYNetHelper exchangesCCY1:self.ccy1 ccy1Amount:self.amount ccy1_wallet_id:self.walletsId ccy2:self.ccy2 ccy2_wallet_id:self.walletsId callback:^(JFResultVo *resultVo) {
        
        [SLRemindView hideHUDForView:weakSelf.view animated:YES];
        
        if (!resultVo.errorNo) {
            NSDictionary *dic = resultVo.results;
            weakSelf.ccy2Amount.text = [NSString stringWithFormat:@"%.8f", [dic[@"ccy2Amount"] doubleValue]];
            weakSelf.rate1.text = [NSString stringWithFormat:@"1 %@ = %.5f %@", dic[@"ccy1"], [dic[@"rate"]doubleValue], dic[@"ccy2"]];
            weakSelf.rate2.text = [NSString stringWithFormat:@"1 %@ = %.5f %@", dic[@"ccy2"], 1.0 / [dic[@"rate"] doubleValue], dic[@"ccy1"]];
            weakSelf.expiresSeconds = [[NSDate dateWithString:dic[@"expiry_datetime_utc"] format:@"yyyy-MM-dd HH:mm:ss"] timeIntervalSince1970] - [[NSDate dateWithString:dic[@"quote_datetime_utc"] format:@"yyyy-MM-dd HH:mm:ss"] timeIntervalSince1970];
            [weakSelf updateExpiresSeconds];

            weakSelf.timeLabel.text = dic[@"quote_datetime_utc"];
            [weakSelf tradable_min_ccy1_amount:[dic[@"tradable_min_ccy1_amount"] floatValue]];
            
            weakSelf.tradeButton.enabled = [dic[@"tradable"] boolValue];
            weakSelf.traderId = dic[@"trade_id"];
        }
    }];
}

- (void)tradeRequest {
    WEAKSELF
    [SLRemindView showHUDAddedTo:self.view animated:YES];
    [HYNetHelper exchangesTrade:self.traderId callback:^(JFResultVo *resultVo) {
        [SLRemindView hideHUDForView:weakSelf.view animated:YES];
        
        if (!resultVo.errorNo) {
            NSString *transfer_id = resultVo.results[@"ccy1_transfer_id"];
            
            NSString *string = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@", JFMainLocalizedString(@"exchange.description1"), self.amount, self.ccy1, JFMainLocalizedString(@"exchange.description2"), self.ccy2Amount.text, self.ccy2];
            NSRange range = [string rangeOfString:@"into"];
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:string];
            [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xFFA000)} range:NSMakeRange(range.location + range.length, string.length - range.location - range.length)];
            
            FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"alert_icon1"] title:JFMainLocalizedString(@"exchange.exchange-success") customView:nil message:string];
            alertController.messageAttStr = attStr;
            alertController.showCloseBtn = YES;
            alertController.messageAlignment = NSTextAlignmentCenter;
            
            FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.See-Details") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
                [weakSelf pushExchangeDetailsVC:transfer_id];
                                }];
            [alertController addAction:action];
            [weakSelf presentViewController:alertController animated:YES completion:nil];
        }else {
            FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"alert_icon_failed"] title:@"Exchange Failed" customView:nil message:nil];
            alertController.showCloseBtn = YES;
            alertController.messageAlignment = NSTextAlignmentCenter;
            
            FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.ok") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
                                }];
            [alertController addAction:action];
            [weakSelf presentViewController:alertController animated:YES completion:nil];
        }
    }];
}

- (void)updateExpiresSeconds {
    WEAKSELF
    if (self.expiresSeconds > 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.expiresSeconds -= 1;
            [weakSelf updateTimeLabel];
            [weakSelf updateExpiresSeconds];
        });
    }
}

- (void)updateTimeLabel {
    NSString *string = [NSString stringWithFormat:@"%@ %ld %@", JFMainLocalizedString(@"exchange.expires-in"), self.expiresSeconds, JFMainLocalizedString(@"exchange.seconds")];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:string];
    [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xFFA000)} range:[string rangeOfString:@(self.expiresSeconds).stringValue]];
    self.expiresLabel.attributedText = attStr;
}

- (void)tradable_min_ccy1_amount:(CGFloat)amount {
    if (amount > self.amount.doubleValue) {
        NSString *string = [NSString stringWithFormat:JFMainLocalizedString(@"exchange_higher_amount_holder"), amount, self.ccy1];
        NSRange range = [string rangeOfString:@"is"];
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:string];
        [attStr addAttributes:@{NSForegroundColorAttributeName: UIColorFromHex(0xFFA000)} range:NSMakeRange(range.location + range.length, string.length - range.length - range.location)];
        
        FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"alert_icon_failed"] title:string customView:nil message:nil];
        alertController.messageAttStr = attStr;
        alertController.showCloseBtn = YES;
        alertController.messageAlignment = NSTextAlignmentCenter;
        
        FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.ok") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
                            }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (IBAction)tradeAction:(id)sender {
    if (self.expiresSeconds == 0) {
        FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"prompt_icon"] title:JFMainLocalizedString(@"exchange.expires-out") customView:nil message:nil];
        alertController.showCloseBtn = YES;
        alertController.messageAlignment = NSTextAlignmentCenter;
        
        WEAKSELF
        FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.get-new-quote") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
            [weakSelf request];
                            }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        [self tradeRequest];
    }
}

- (IBAction)cancelAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)pushExchangeDetailsVC:(NSString *)transfer_id {
    ExchangeDetailsViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"ExchangeDetailsViewController"];
    vc.transfer_id = transfer_id;
    [self.navigationController pushViewController:vc animated:YES];
}
@end
